const moment = require("moment");
const math = require("mathjs");
const Tplmsg = require("./../../lib/wxa/tplmsg.class");
const context = require("./../../context");

math.config({
    number: "BigNumber", // Default type of number:
    // 'number' (default), 'BigNumber', or 'Fraction'
    precision: 20 // Number of significant digits for BigNumbers
});

module.exports = {
    async wxaAnalysis(column, wxaId, num = 1) {
        const refDate = moment().format("YYYYMMDD");
        const analysis = await doodoo
            .model("analysis_wxa_daily_summary")
            .query(qb => {
                qb.where("ref_date", refDate);
                qb.where("wxa_id", wxaId);
            })
            .fetch();
        if (analysis) {
            await doodoo
                .model("analysis_wxa_daily_summary")
                .forge({
                    id: analysis.id,
                    [column]: math.format(
                        math.eval(`${num} + ${analysis[column]}`)
                    )
                })
                .save();
        } else {
            await doodoo
                .model("analysis_wxa_daily_summary")
                .forge({
                    wxa_id: wxaId,
                    ref_date: refDate,
                    [column]: num
                })
                .save();
        }
    },

    async analysis(column, num = 1) {
        const refDate = moment().format("YYYYMMDD");
        const analysis = await doodoo
            .model("analysis_daily_summary")
            .query(qb => {
                qb.where("ref_date", refDate);
            })
            .fetch();
        if (analysis) {
            await doodoo
                .model("analysis_daily_summary")
                .forge({
                    id: analysis.id,
                    [column]: math.format(
                        math.eval(`${num} + ${analysis[column]}`)
                    )
                })
                .save();
        } else {
            await doodoo
                .model("analysis_daily_summary")
                .forge({
                    ref_date: refDate,
                    [column]: num
                })
                .save();
        }
    },

    addTrade() {
        doodoo.hook.run("analysis", "trade");
    },

    async wxaAnalysisUser(wxaId, userId) {
        const refDate = moment().format("YYYYMMDD");
        const analysis = await doodoo
            .model("analysis_product_user_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("user_id", userId);
                qb.where("ref_date", refDate);
            })
            .fetch();
        const analysisWxa = await doodoo
            .model("analysis_wxa_daily_summary")
            .query(qb => {
                qb.where("wxa_id", wxaId);
                qb.where("ref_date", refDate);
            })
            .fetch();
        if (!analysis) {
            await doodoo
                .model("analysis_product_user_summary")
                .forge({
                    ref_date: refDate,
                    wxa_id: wxaId,
                    user_id: userId
                })
                .save();
            if (analysisWxa) {
                await doodoo
                    .model("analysis_wxa_daily_summary")
                    .forge({
                        id: analysisWxa.id,
                        visitor: math.format(
                            math.eval(`1 + ${analysisWxa.visitor}`)
                        )
                    })
                    .save();
            } else {
                await doodoo
                    .model("analysis_wxa_daily_summary")
                    .forge({
                        ref_date: refDate,
                        wxa_id: wxaId,
                        visitor: 1
                    })
                    .save();
            }
        }
    },

    async addTplMsg(wxa_id, tpl_title_id, keyword_id_list) {
        const tplMsg = new Tplmsg(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );
        // 获取小程序信息，刷新accessToken
        let wxa = await doodoo
            .model("wxa")
            .query(qb => {
                qb.where("id", wxa_id);
            })
            .fetch();
        wxa = await context.checkWxaAuthorizerAccessToken(wxa);

        console.log("addTplMsg");
        console.log(wxa);

        // 添加模版消息
        const tpl = await doodoo
            .model("wxa_tplmsg")
            .query(qb => {
                qb.where("wxa_id", wxa.id);
                qb.where("title_id", tpl_title_id);
                qb.where("keyword_id", keyword_id_list);
            })
            .fetch();
        if (!tpl) {
            const result = await tplMsg.add_tplmsg(
                wxa.authorizer_access_token,
                tpl_title_id,
                keyword_id_list
            );
            if (result.errmsg === "ok") {
                const wxaTplmsg = await doodoo
                    .model("wxa_tplmsg")
                    .forge({
                        wxa_id: wxa.id,
                        title_id: tpl_title_id,
                        keyword_id: keyword_id_list,
                        tpl_id: result.template_id
                    })
                    .save();
                console.log("新增模版消息成功", wxaTplmsg);
                return wxaTplmsg;
            } else {
                console.log("新增模版消息失败", result);
                return false;
            }
        } else {
            console.log("模版消息已存在", tpl);
            return tpl;
        }
    },

    async sendTplMsg(wxa_id, openid, tpl_id, form_id, data, page, keyword) {
        const tplMsg = new Tplmsg(
            process.env.OPEN_APPID,
            process.env.OPEN_APPSECRET
        );
        // 获取小程序信息，刷新accessToken
        let wxa = await doodoo
            .model("wxa")
            .query(qb => {
                qb.where("id", wxa_id);
            })
            .fetch();
        wxa = await context.checkWxaAuthorizerAccessToken(wxa);

        console.log("sendTplMsg");
        console.log({
            authorizer_access_token: wxa.authorizer_access_token,
            openid,
            tpl_id,
            form_id,
            data,
            page,
            keyword
        });

        // 发送模版消息
        const result = await tplMsg.send_tplmsg(
            wxa.authorizer_access_token,
            openid,
            tpl_id,
            form_id,
            data,
            page,
            keyword
        );
        console.log("模版消息结果", result);
        if (result.errmsg === "ok") {
            console.log("发送成功");
        } else {
            console.log("发送失败");
        }
    }
};
